import 'package:flutter/material.dart';
import '../Search.dart';
import '../../components/MyDialog.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _msg = "";
  _getData() async {
    //'jd.itying.com/api/httpGet'
    try {
      var apiUrl = Uri.parse('https://jd.itying.com/api/httpGet');
      var response = await http.get(apiUrl);
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');
      print(response.body is String);
      setState(() {
        this._msg = json.decode(response.body)["msg"];
      });
    } catch (e) {
      print(e);
    }
  }

  _postData() async {
    var apiUrl = Uri.parse('https://jd.itying.com/api/httpPost');
    var response =
        await http.post(apiUrl, body: {'username': '张三', 'age': '20'});
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
    print(response.body is String);

    // print(await http.read(Uri.parse('https://example.com/foobar.txt')));
  }

  @override
  void initState() {
    super.initState();
    // Map userInfo = {"username": "张三", "age": 20};
    // var a = json.encode(userInfo); //map类型=>json字符串
    // print(userInfo is Map);
    // print(a is String);
    String userInfo = '{"username": "张三", "age": "20"}';
    Map u = json.decode(userInfo); //json字符串=>map类型
    print(u["username"]);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(_msg),
        ElevatedButton(
          onPressed: this._getData,
          child: Text("Get请求"),
        ),
        ElevatedButton(
          onPressed: _postData,
          child: Text("Post请求"),
        ),
        ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, '/http');
          },
          child: Text("Get请求数据丶渲染数据演示demo"),
        ),
        ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, '/refresh');
          },
          child: Text("下拉刷新触底加载demo"),
        ),
      ],
    );
  }
}
